package Servlet.MainPage;

import BaseClass.PetInfo;
import DataBase.DataBase;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 搜索自动补全
 */
@WebServlet("/AutoComplete")
public class AutoCompleteServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端传入的数据
        String keyword = req.getParameter("text");
        boolean haveSearched = DataBase.getSearched(keyword);

        List<PetInfo> petInfo = DataBase.getSearchResult(keyword);

        String str = "";
        for(int i=0;i<petInfo.size();i++){
            str += petInfo.get(i).getPetName();
            if(i != petInfo.size()-1) str += ",";
        }
        if(haveSearched) {
            //将处理好的数据传回给客户
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write(str);
        }
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}